package com.newshub.admin.controller;

import com.newshub.common.Result;
import com.newshub.common.fetch.FetchResult;
import com.newshub.common.fetch.FetchTask;
import com.newshub.business.dto.PageResult;
import com.newshub.monitor.dto.TaskWithSuccessRate;
import com.newshub.admin.service.FetchTaskService;
import com.newshub.admin.service.AsyncFetchService;
import com.newshub.admin.entity.RssFeed;
import com.newshub.admin.mapper.RssFeedMapper;
import com.newshub.logging.annotation.BusinessLog;
import com.newshub.logging.annotation.LogLevel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/admin/fetch-tasks")
@CrossOrigin(origins = "*")
public class AdminFetchTaskController {

    @Autowired
    private FetchTaskService fetchTaskService;
    
    @Autowired
    private FetchTask rssFetchTask;
    
    @Autowired
    private AsyncFetchService asyncFetchService;
    
    @Autowired
    private RssFeedMapper rssFeedMapper;

    @GetMapping("/page")
    @BusinessLog(module = "抓取任务管理", description = "分页查询抓取任务列表", level = LogLevel.INFO)
    public Result<Map<String, Object>> page(@RequestParam(required = false) Integer pageNum,
                                            @RequestParam(required = false) Integer pageSize,
                                            @RequestParam(required = false) Integer status) {
        try {
            List<Map<String, Object>> list = fetchTaskService.listTasks(pageNum, pageSize, status);
            Long total = fetchTaskService.countTasks(status);
            Map<String, Object> data = new HashMap<>();
            data.put("list", list);
            data.put("total", total);
            data.put("pageNum", pageNum == null ? 1 : pageNum);
            data.put("pageSize", pageSize == null ? 10 : pageSize);
            return Result.success(data);
        } catch (Exception e) {
            return Result.error("查询失败: " + e.getMessage());
        }
    }
    
    /**
     * 分页查询任务列表，包含成功率信息
     */
    @GetMapping("/page-with-success-rate")
    @BusinessLog(module = "抓取任务管理", description = "分页查询任务列表（含成功率）", level = LogLevel.INFO)
    public Result<PageResult<TaskWithSuccessRate>> pageWithSuccessRate(
            @RequestParam(required = false) Integer pageNum,
            @RequestParam(required = false) Integer pageSize,
            @RequestParam(required = false) Integer status,
            @RequestParam(value = "days", defaultValue = "7") Integer days) {
        try {
            // 验证天数参数
            if (days != 7 && days != 14 && days != 30) {
                return Result.error("天数参数只能是7、14或30");
            }
            
            PageResult<TaskWithSuccessRate> result = fetchTaskService.getTasksWithSuccessRate(status, days, pageNum, pageSize);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("查询失败: " + e.getMessage());
        }
    }
    
    /**
     * 手动触发抓取任务（异步）
     */
    @PostMapping("/{feedId}/trigger")
    @BusinessLog(module = "抓取任务管理", description = "手动触发抓取任务", level = LogLevel.INFO)
    public Result<Map<String, Object>> triggerFetch(@PathVariable Long feedId) {
        try {
            // 1. 先更新最后抓取时间（防止重复触发）
            RssFeed feed = rssFeedMapper.selectById(feedId.intValue());
            if (feed != null) {
                feed.setLastFetchDate(LocalDate.now());
                feed.setLastFetchAt(LocalDateTime.now());
                rssFeedMapper.update(feed);
                log.info("手动触发抓取任务，已更新RSS源状态，feedId: {}, feedName: {}", feedId, feed.getName());
            }
            
            // 2. 异步执行抓取任务
            String taskId = asyncFetchService.executeFetchAsync(feedId);
            
            Map<String, Object> data = new HashMap<>();
            data.put("taskId", taskId);
            data.put("message", "抓取任务已提交，正在后台执行");
            
            return Result.success(data);
        } catch (Exception e) {
            return Result.error("触发抓取任务失败: " + e.getMessage());
        }
    }
    
    /**
     * 查询抓取任务状态
     */
    @GetMapping("/task/{taskId}/status")
    @BusinessLog(module = "抓取任务管理", description = "查询抓取任务状态", level = LogLevel.INFO)
    public Result<FetchResult> getTaskStatus(@PathVariable String taskId) {
        try {
            FetchResult result = asyncFetchService.getFetchResult(taskId);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("查询任务状态失败: " + e.getMessage());
        }
    }
}




